from django.core.urlresolvers import reverse
from django.db import transaction
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect
from django.template import RequestContext

from common.paginator import paginate

from issues.forms import IssueCreateForm, IssueEditForm, SearchForm, IssueFormSet
from issues.models import Issue, Importance, Urgency, Attachment
from issues.search import search

from projects.views import get_project

def issue_list(request, project_slug, template_name='issues/issue_list.html'):
    project = get_project(request, project_slug)
    issues = paginate(request, project.issues.all())
    return render_to_response(template_name, 
                              {'issues': issues,
                               'project': project,},
                               context_instance=RequestContext(request))

@transaction.commit_on_success
def create_issue(request, project_slug, template_name='issues/issue_form.html'):
    project = get_project(request, project_slug)
    if request.method == 'POST':
        form = IssueCreateForm(request.POST)
        if form.is_valid():
            issue = form.save(commit=False)
            issue.status = 'new'
            issue.creator = request.user
            issue.project = project
            issue.save()
            return HttpResponseRedirect(reverse('issue_detail', args=[project.slug, str(issue.id)]))
    else:
        form = IssueCreateForm()
    return render_to_response(template_name,
                              {'form': form,
                               'project': project},
                              context_instance=RequestContext(request))

def issue_detail(request, project_slug, issue_id, template_name='issues/issue_detail.html'):
    """
    Non-members get the read-only display.
    Members get the editable display.
    """
    project = get_project(request, project_slug)
    issue = get_object_or_404(Issue, pk=issue_id, project=project)
    context = {'project': project,
               'issue': issue}
    if request.user in project.members.all():
        if request.method == 'POST':
            form = IssueEditForm(request.POST, instance=issue)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('issue_detail', args=[project.slug, str(issue.id)]))
        else:
            form = IssueEditForm(instance=issue)
        context['form'] = form
    return render_to_response(template_name,
                              context,
                              context_instance=RequestContext(request))

def urgency(request, key, template_name='issues/urgency_details.html'):
    # Should probably just be a generic view -- CRUD should be through admin screen only
    requested_urgency = get_object_or_404(Urgency, pk=key)
    return render_to_response(template_name, {'urgency': requested_urgency})
    
def importance(request, key, template_name='issues/importance_details.html'):
    # Should probably just be a generic view -- CRUD should be through admin screen only
    requested_importance = get_object_or_404(Importance, pk=key)
    return render_to_response(template_name, {'importance': requested_importance})
    
def attachment(request, key, template_name='issues/attachment_details.html'):
    # Could be a generic view, but we'd likely want some syntax colorization
    requested_attachment = get_object_or_404(Attachment, pk=key)
    return render_to_response(template_name, {'attachment': requested_attachment})

def issues_search(request, form_class=SearchForm, template_name='issues/search.html'):
    form = None
    if request.method == 'POST':
        #do search
        form = form_class(request.POST)
        if form.is_valid():
            results = search(form.cleaned_data)
            if results:
                return render_to_response(template_name, {'form': form, 'issues': results})
    else:
        form = form_class()
    return render_to_response(template_name, {'form': form})
    
def triage(request, template_name='issues/triage_form.html'):
    if request.method == 'POST':
        formset = IssueFormSet(request.POST)
        if formset.is_valid():
            instances = formset.save()
            return HttpResponseRedirect('/issues/triage/')
    else:
        formset = IssueFormSet()
    return render_to_response(template_name, {'formset': formset})
